package com.dxq.basic_ui_library;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zsh
 * @date 2020/2/19.
 * 功能：输入框模糊搜索加载
 */

public class SearchView<T> extends FrameLayout {

    private Context mContext;
    private View mView;
    private LinearLayout llView;
    private EditText mEtInput;
    private ImageView mImageView, iv;
    private ListView listView;
    private SpinnerPopWindow mSpinnerPopWindow;
    private PopupWindow popupWindow = null;
    private List<T> spinnerList = new ArrayList<>();
    private boolean isShow = false;
    private int inputBg;
    private int height;
    private String inputHint;
    private int inputSize;
    private int inputColor;
    private int inputHintColor;
    private int clearIcon;
    private int popHeight;//下拉框展示高度
    private Integer itemSize;//展示下拉框中的item条数

    public SearchView(Context context) {
        super(context);
        init(context, null);
    }

    public SearchView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public SearchView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public SearchView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }

    //初始化
    private void init(Context context, AttributeSet attrs) {
        mContext = context;
        if (attrs == null) return;
        //获取自定义属性
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.SearchView);
        //输入框背景
        inputBg = typedArray.getResourceId(R.styleable.SearchView_input_background, R.drawable.input_bg);
        //输入框高度
        height = typedArray.getDimensionPixelOffset(R.styleable.SearchView_height, 40);
        //提示内容
        inputHint = typedArray.getString(R.styleable.SearchView_input_hint);
        //字体大小
        inputSize = typedArray.getDimensionPixelSize(R.styleable.SearchView_input_size, 20);
        //字体颜色
        inputColor = typedArray.getColor(R.styleable.SearchView_input_color, Color.BLACK);
        //提示字体颜色
        inputHintColor = typedArray.getColor(R.styleable.SearchView_input_hint_color, Color.GRAY);
        //清空按钮
        clearIcon = typedArray.getResourceId(R.styleable.SearchView_image_icon, R.drawable.clear);
        //下拉框高度
        popHeight = typedArray.getDimensionPixelSize(R.styleable.SearchView_pop_height, 150);
        //下拉框条数
        itemSize = typedArray.getInteger(R.styleable.SearchView_item_size, 6);
        typedArray.recycle();

        mView = LayoutInflater.from(context).inflate(R.layout.search_view, this, false);
        llView = (LinearLayout) mView.findViewById(R.id.ll_view);
        mEtInput = (EditText) mView.findViewById(R.id.et_input);
        mImageView = (ImageView) mView.findViewById(R.id.iv_icon);
        addView(mView);

        //布局关联属性
        llView.setBackgroundResource(inputBg);
        //llView.setMinimumHeight(height);
        mEtInput.setHint(inputHint);
        mEtInput.setTextSize(TypedValue.COMPLEX_UNIT_PX, inputSize);
        mEtInput.setTextColor(inputColor);
        mEtInput.setHintTextColor(inputHintColor);
        mImageView.setImageResource(clearIcon);


        if (getInputContent().equals("")) {
            mImageView.setVisibility(INVISIBLE);
        }

        mEtInput.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().equals("")) {
                    mImageView.setVisibility(INVISIBLE);
                } else {
                    mImageView.setVisibility(VISIBLE);
                    if (!isShow) {
                        if (null != spinnerItemListener)
                            spinnerItemListener.editChange(s.toString());
                    }
                }
                isShow = false;
            }
        });

        mImageView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                //mClearContent.clear();
                mEtInput.setText("");
            }
        });

    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);
//        //设置宽高
//        setMeasuredDimension(width, height);
    }
    //根据xml的设定获取宽度
    private int measureWidth(int measureSpec) {
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        //如果没有指定大小
        if (specMode == MeasureSpec.UNSPECIFIED) {
            //specSize = defaultSize;
        }
        //wrap_content
        if (specMode == MeasureSpec.AT_MOST){

        }
        //fill_parent或者精确值
        else if (specMode == MeasureSpec.EXACTLY){

        }
        return specSize;
    }
    //根据xml的设定获取高度
    private int measureHeight(int measureSpec) {
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);
        LogUtils.iTag("specSize=="+specSize);
        //如果没有指定大小
        if (specMode == MeasureSpec.UNSPECIFIED) {
            //specSize = defaultSize;
        }
        //wrap_content
        if (specMode == MeasureSpec.AT_MOST){
            int editHeight = mEtInput.getPaddingTop() + mEtInput.getPaddingBottom() + mEtInput.getHeight();
            int iconHeight = mImageView.getPaddingTop() + mImageView.getPaddingBottom() + mImageView.getHeight();
            specSize = Math.max(editHeight, iconHeight);
        }
        //fill_parent或者精确值
        else if (specMode == MeasureSpec.EXACTLY){
            //无需处理
        }
        return specSize;
    }

    /**
     * 1.当输入框输入内容后显示pop
     * 2.当用户点击pop中的一项后editText更改为选中的内容，同时pop消失
     * 3.当删除editText内数据为空后，pop消失
     *
     * @param spinnerList
     */
    public void initSpinnerPopWindow(final List<T> spinnerList) {
        this.spinnerList = spinnerList;
        //展开
        if (spinnerList.size() > 0) {
            openPopWindow();
        }
    }

    //展开list
    private void openPopWindow() {
        // 加载popupWindow的布局文件
        String infServie = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater layoutInflater;
        layoutInflater = (LayoutInflater) getContext().getSystemService(infServie);
        View contentView = layoutInflater.inflate(R.layout.list_view, null, false);
        listView = (ListView) contentView.findViewById(R.id.listView);
        listView.setAdapter(new SearchAdapter());
        if (spinnerList.size() >= itemSize) {
            popupWindow = new PopupWindow(contentView, this.getWidth(), SizeUtils.dp2px(popHeight));
        } else {
            popupWindow = new PopupWindow(contentView, this.getWidth(), LayoutParams.WRAP_CONTENT);
        }
        popupWindow.setBackgroundDrawable(getResources().getDrawable(android.R.color.transparent));
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAsDropDown(this);


    }

    //关闭list
    private void closePopWindow() {
        popupWindow.dismiss();
        popupWindow = null;
    }

    //设置内容
    public void setTextContent(T t) {
        isShow = true;
        mEtInput.setText(t.toString());
        spinnerItemListener.itemClick(t);
    }

    /**
     * 获取输入框输入内容
     *
     * @return
     */
    public String getInputContent() {
        return mEtInput.getText().toString().trim();
    }

    public interface SpinnerItemListener<T> {

        void itemClick(T t);

        void editChange(String string);
    }

    public SpinnerItemListener spinnerItemListener;

    public void setSpinnerItemListener(SpinnerItemListener spinnerItemListener) {
        this.spinnerItemListener = spinnerItemListener;
    }

    class SearchAdapter extends BaseAdapter {

        public SearchAdapter() {
        }

        public void addList(List<T> list) {
            if (list != null) {
                spinnerList.addAll(list);
            }
            notifyDataSetChanged();
        }

        public void reAddList(List<T> list) {
            spinnerList = list;
            notifyDataSetChanged();
        }

        public void addLast(List<T> list) {
            spinnerList.addAll(list);
        }

        public void clearList() {
            spinnerList.clear();
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return spinnerList.size();
        }

        @Override
        public T getItem(int position) {
            return spinnerList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final T t = getItem(position);
            ItemHolder itemHolder = null;
            if (convertView == null) {
                convertView = View.inflate(mContext, R.layout.spinner_item_layout, null);
                itemHolder = new ItemHolder(convertView);
            }
            itemHolder = (ItemHolder) convertView.getTag();
            itemHolder.msg.setText(t.toString());//序号

            itemHolder.msg.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    setTextContent(t);
                    closePopWindow();
                }
            });

            return convertView;
        }

        class ItemHolder {
            TextView msg;

            public ItemHolder(View view) {
                msg = (TextView) view.findViewById(R.id.tv_name);
                view.setTag(this);
            }
        }
    }
}
